package com.qqtech.qquan.send.controller;

import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.agent.context.AdminPage;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.send.enums.SendDeliveryUserAuditStatusDictEnum;
import com.qqtech.qquan.send.enums.SendDeliveryUserStatusDictEnum;
import com.qqtech.qquan.send.model.SendDeliveryUser;
import com.qqtech.qquan.send.model.SendDeliveryUserQuery;
import com.qqtech.qquan.send.model.SendDeliveryUserVo;
import com.qqtech.qquan.send.service.SendDeliveryUserService;
import com.qqtech.qquan.sys.controller.BaseAgentController;
import com.qqtech.qquan.user.enums.UserAuthAuditStatusDictEnum;
import com.qqtech.qquan.user.model.UserAuth;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.service.UserAuthService;
import com.qqtech.qquan.user.service.UserBaseService;

@Controller
@RequestMapping(value = "/send/deliveryUser")
public class SendDeliveryUserController extends BaseAgentController {
	
	@Resource
	private SendDeliveryUserService sendDeliveryUserService;
	
	@Resource
	private CommunityBaseService communityBaseService;
	
	@Resource
	private UserBaseService userBaseService;
	
	@Resource
	private UserAuthService userAuthService;
	
	@Override
	protected BaseService<SendDeliveryUser> getBaseService() {
		return sendDeliveryUserService;
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		return "/send/deliveryUser-list";
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(SendDeliveryUserQuery query, HttpServletRequest request,
			HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		query.setCommunityId(super.getCurrCommunityId());//当前后台用户的社区id
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(),
				new PageOrder(Direction.DESC, "id"));
		Page<SendDeliveryUserVo> page = sendDeliveryUserService.queryPageListByAdmin(query,
				pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Model model) {
		Integer communityId = super.getCurrCommunityId();
		CommunityBaseVo community = communityBaseService.getById(communityId);
		if (community != null) {
			model.addAttribute("community", community);
		}
			
		return "/send/deliveryUser-update";
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(SendDeliveryUserVo sendDeliveryUserVo, HttpServletRequest request,
			HttpServletResponse response) {
		Result ret = new Result();
		if (sendDeliveryUserVo == null) {
			ret.addErr("参数不能为空");
		} else {
			if (sendDeliveryUserVo.getUserId() == null) {
				ret.addErr("请选择用户");
			} else {
				UserAuth userAuth = userAuthService.getByUserId(sendDeliveryUserVo.getUserId());
				if (userAuth == null || userAuth.getAuditStatus().intValue() != UserAuthAuditStatusDictEnum.THROUGH.getCode()) {
					ret.addErr("该用户还没有实名认证");
				}
			}
			if (ret.checkForm() && sendDeliveryUserVo.getCommunityId() == null) {
				ret.addErr("请选择社区");
			}
			if (ret.checkForm() && sendDeliveryUserVo.getParentId() != null) {
				SendDeliveryUser parent = sendDeliveryUserService.getById(sendDeliveryUserVo.getParentId());
				if (parent != null && sendDeliveryUserVo.getCommunityId() != null && parent.getCommunityId().intValue() != sendDeliveryUserVo.getCommunityId()) {
					ret.addErr("所选的社区和上级配送人不在同一个社区");
				}
			} else if (ret.checkForm()) {
				SendDeliveryUserQuery sendDeliveryUserQuery = new SendDeliveryUserQuery();
				sendDeliveryUserQuery.setCommunityId(sendDeliveryUserVo.getCommunityId());
				sendDeliveryUserQuery.setParentId(0);
				int count = sendDeliveryUserService.queryCount(sendDeliveryUserQuery);
				if (count >= 1) {
					ret.addErr("该社区已有顶级配送人员，请选择上级配送人");
				}
			}
		}
		if (ret.checkForm()) {
			Timestamp now = TimeUtil.now();
			SendDeliveryUser entity = new SendDeliveryUser();
			entity.setUserId(sendDeliveryUserVo.getUserId());
			entity.setAuditAt(now);
			entity.setAuditStatus(SendDeliveryUserAuditStatusDictEnum.THROUGH.getCode());
			entity.setCommunityId(sendDeliveryUserVo.getCommunityId());
			entity.setNewAt(now);
			if (sendDeliveryUserVo.getParentId() == null) {
				entity.setParentId(0);
			} else {
				entity.setParentId(sendDeliveryUserVo.getParentId());
			}
			if (sendDeliveryUserVo.getParentUserId() == null) {
				entity.setParentUserId(0);
			} else {
				entity.setParentUserId(sendDeliveryUserVo.getParentUserId());
			}
			if (sendDeliveryUserVo.getHasSuperPower() == null) {
				entity.setHasSuperPower(YesNoEnum.NO.getCode());
			} else {
				entity.setHasSuperPower(sendDeliveryUserVo.getHasSuperPower());
			}
			entity.setStatus(SendDeliveryUserStatusDictEnum.OPEN.getCode());
			sendDeliveryUserService.insert(entity);
		}
		return ret;
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) {
		SendDeliveryUserVo entity = sendDeliveryUserService.getById(id);
		if (entity != null && entity.getCommunityId() != null) {
			CommunityBaseVo community = communityBaseService.getById(entity.getCommunityId());
			if (community != null) {
				entity.setCommunityName(community.getName());
			}
			UserBase userBase = userBaseService.getById(entity.getUserId());
			if (userBase != null) {
				entity.setUserNick(userBase.getNick());
			}
			/*if (entity.getParentId().intValue() != 0) {
				SendDeliveryUserVo entityParent = sendDeliveryUserService.getById(entity.getParentId());
				if (entityParent != null) {
					UserBase userBaseParent = userBaseService.getById(entityParent.getUserId());
					entity.setParentNick(userBaseParent.getNick());
				}
			}*/
			if (entity.getParentUserId().intValue() != 0) {
				UserBase userBaseParent = userBaseService.getById(entity.getParentUserId());
				entity.setParentNick(userBaseParent.getNick());
			}
		}else{
			Integer communityId = super.getCurrCommunityId();
			CommunityBaseVo community = communityBaseService.getById(communityId);
			if (community != null) {
				request.setAttribute("community", community);
			}
		}
		request.setAttribute("entity", entity);
		return "/send/deliveryUser-update";
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(SendDeliveryUserVo sendDeliveryUserVo) {
		Result ret = new Result();
		if (sendDeliveryUserVo == null || sendDeliveryUserVo.getId() == null) {
			ret.addErr("参数不能为空");
		} else {
			if (sendDeliveryUserVo.getCommunityId() == null) {
				ret.addErr("请选择社区");
			}
			if (ret.checkForm() && sendDeliveryUserVo.getParentId() != null) {
				SendDeliveryUser parent = sendDeliveryUserService.getById(sendDeliveryUserVo.getParentId());
				if (parent != null && sendDeliveryUserVo.getCommunityId() != null && parent.getCommunityId().intValue() != sendDeliveryUserVo.getCommunityId()) {
					ret.addErr("所选的社区和上级配送人不在同一个社区");
				}
			} else if (ret.checkForm()) {
				SendDeliveryUserQuery sendDeliveryUserQuery = new SendDeliveryUserQuery();
				sendDeliveryUserQuery.setCommunityId(sendDeliveryUserVo.getCommunityId());
				sendDeliveryUserQuery.setParentId(0);
				List<SendDeliveryUserVo> list = sendDeliveryUserService.queryList(sendDeliveryUserQuery);
				if (list != null && !list.isEmpty()) {
					SendDeliveryUserVo superUser = list.get(0);
					if (superUser.getId().intValue() != sendDeliveryUserVo.getId()) {
						ret.addErr("该社区已有顶级配送人员，请选择上级配送人");
					}
				}
			}
		}
		if (ret.checkForm()) {
			SendDeliveryUser entity = new SendDeliveryUser();
			entity.setId(sendDeliveryUserVo.getId());
			if (sendDeliveryUserVo.getParentId() == null) {
				entity.setParentId(0);
			} else {
				entity.setParentId(sendDeliveryUserVo.getParentId());
			}
			if (sendDeliveryUserVo.getParentUserId() == null) {
				entity.setParentUserId(0);
			} else {
				entity.setParentUserId(sendDeliveryUserVo.getParentUserId());
			}
			if (sendDeliveryUserVo.getHasSuperPower() == null) {
				entity.setHasSuperPower(YesNoEnum.NO.getCode());
			} else {
				entity.setHasSuperPower(sendDeliveryUserVo.getHasSuperPower());
			}
			entity.setCommunityId(sendDeliveryUserVo.getCommunityId());
			sendDeliveryUserService.updateById(entity);
		}
		return ret;
	}
	
	@RequestMapping(value = "/setStatus", method = RequestMethod.POST)
	@ResponseBody
	public Result setStatus(@RequestBody SendDeliveryUserVo sendDeliveryUserVo) {
		Result ret = new Result();
		if (sendDeliveryUserVo == null || sendDeliveryUserVo.getId() == null || sendDeliveryUserVo.getStatus() == null) {
			ret.addErr("参数不能为空");
		}
		if (ret.checkForm()) {
			SendDeliveryUser entity = new SendDeliveryUser();
			entity.setId(sendDeliveryUserVo.getId());
			entity.setStatus(sendDeliveryUserVo.getStatus());
			sendDeliveryUserService.updateById(entity);
		}
		return ret;
	}
	
	@RequestMapping(value = "/setAuditStatus", method = RequestMethod.POST)
	@ResponseBody
	public Result setAuditStatus(@RequestBody SendDeliveryUserVo sendDeliveryUserVo) {
		Result ret = new Result();
		if (sendDeliveryUserVo == null || sendDeliveryUserVo.getId() == null || sendDeliveryUserVo.getAuditStatus() == null) {
			ret.addErr("参数不能为空");
		}
		if (ret.checkForm()) {
			SendDeliveryUser entity = new SendDeliveryUser();
			entity.setId(sendDeliveryUserVo.getId());
			Timestamp now = TimeUtil.now();
			entity.setAuditAt(now);
			entity.setAuditStatus(sendDeliveryUserVo.getAuditStatus());
			sendDeliveryUserService.updateById(entity);
		}
		return ret;
	}
	
	/**
	 * 提供一个选择配送人的页面
	 * @param model
	 * @author Ami
	 * @return
	 */
	@RequestMapping(value = "/choose", method = RequestMethod.GET)
	public String choose(Model model) {
		return "/send/deliveryUser-choose";
	}
	
	/**
	 * 提供一个选择配送人的页面
	 * @author Ami
	 * @return
	 */
	@RequestMapping(value = "/choose", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage choose(SendDeliveryUserQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "id"));
		Page<SendDeliveryUserVo> page = sendDeliveryUserService.queryPageListByAdmin(query, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}
}
